package com.cardbaobao.cardbabyclient.base;
import android.app.Application;
import android.content.Context;
import android.support.multidex.MultiDex;

import com.cardbaobao.cardbabyclient.BuildConfig;
import com.cardbaobao.cardbabyclient.model.BuriedData;
import com.cardbaobao.cardbabyclient.model.UserInfo;
import com.cardbaobao.cardbabyclient.utils.LogUtils;
import com.cardbaobao.cardbabyclient.utils.PhoneInfoUtil;
import com.cardbaobao.cardbabyclient.utils.SharedPreferencesUtil;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.Tracker;
import com.tencent.tinker.loader.app.ApplicationLike;
import com.tinkerpatch.sdk.TinkerPatch;
import com.tinkerpatch.sdk.loader.TinkerPatchApplicationLike;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;

import cn.jpush.android.api.JPushInterface;

/**
 * CbbApplication
 * 2016/7/27 9:15
 */
public class App extends Application {
    private static final String TAG="APP";
    //用户信息、包括用户id、电话等
    private UserInfo mUser;

    public static Context mContext;

    public static App instance;

    @Override
    public void onCreate() {
        super.onCreate();
        //初始化友盟、极光等
        init();
        //初始化微信热修复
        initTinkerPatch();
    }

    private ApplicationLike tinkerApplicationLike;

    private void init(){
        instance = this;
        mContext = getApplicationContext();
        LogUtils.init(BuildConfig.DEBUG);
        //配置友盟
        //参数1:上下文，必须的参数，不能为空
        //参数2:友盟 app key，非必须参数，如果Manifest文件中已配置app key，该参数可以传空，则使用Manifest中配置的app key，否则该参数必须传入
        //参数3:友盟 channel，非必须参数，如果Manifest文件中已配置channel，该参数可以传空，则使用Manifest中配置的channel，否则该参数必须传入
        //参数4:设备类型，必须参数，传参数为UMConfigure.DEVICE_TYPE_PHONE则表示手机；传参数为UMConfigure.DEVICE_TYPE_BOX则表示盒子；默认为手机
        //参数5:Push推送业务的secret，需要集成Push功能时必须传入Push的secret，否则传空
        UMConfigure.init(mContext,
                "58c28a0fa3251140320019cd",
                PhoneInfoUtil.getApkChannelName(mContext),
                UMConfigure.DEVICE_TYPE_PHONE,
                null);
        //友盟调试信息开关
        Config.DEBUG = BuildConfig.DEBUG;
        //友盟分享
        UMShareAPI.get(mContext);
        //新浪微博
        PlatformConfig.setSinaWeibo("4054734256",
                "dcc6c2f63a9a1ad4c2aefa8115764cb7",
                "http://sns.whalecloud.com/sina2/callback");
        //微信 appid appsecret
        PlatformConfig.setWeixin("wxa3e16780ccfd060a",
                "2943b38aec5779842b4e2e394bd16b87");
        //QQ
        PlatformConfig.setQQZone("1104854186",
                "heMImoyBbCR7NJva");
        //友盟统计
        if ("release".equals(BuildConfig.BUILD_TYPE)) {
            //生产环境才使用友盟错误收集
            MobclickAgent.setCatchUncaughtExceptions(true);
            MobclickAgent.setScenarioType(mContext, MobclickAgent.EScenarioType.E_UM_NORMAL);
        }
        MobclickAgent.openActivityDurationTrack(false);//禁止默认的页面统计
        //初始化极光推送
        JPushInterface.init(mContext);
        // Set the dispatch period in seconds.
        GoogleAnalytics.getInstance(mContext).setLocalDispatchPeriod(1);
    }

    private void initTinkerPatch(){
        // 我们可以从这里获得Tinker加载过程的信息
        if (BuildConfig.TINKER_ENABLE) {
            tinkerApplicationLike = TinkerPatchApplicationLike.getTinkerPatchApplicationLike();
            // 初始化TinkerPatch SDK
            TinkerPatch.
                    init(tinkerApplicationLike).
                    reflectPatchLibrary().
                    setPatchRollbackOnScreenOff(true).
                    setPatchRestartOnSrceenOff(true).
                    setFetchPatchIntervalByHours(1);
            // 获取当前的补丁版本
            LogUtils.d(TAG, "Current patch version is " + TinkerPatch.with().getPatchVersion());
            // fetchPatchUpdateAndPollWithInterval 与 fetchPatchUpdate(false)
            // 不同的是，会通过handler的方式去轮询
            TinkerPatch.with().fetchPatchUpdateAndPollWithInterval();
        }
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    //谷歌统计
    private Tracker mTracker;

    synchronized public Tracker getDefaultTracker() {
        if (mTracker == null) {
            GoogleAnalytics analytics = GoogleAnalytics.getInstance(mContext);
            mTracker = analytics.newTracker("UA-10719358-9");
        }
        return mTracker;
    }

    public UserInfo getUser() {
        if (mUser == null) {
            mUser = SharedPreferencesUtil.CbbUserInfo.getUserInfo();
            if (mUser == null) {
                mUser = new UserInfo();
            }
        }
        return mUser;
    }

    public void setUser(UserInfo mUser) {
        this.mUser = mUser;
        //重新设置埋点baseData数据
        BuriedData.initBaseData();
        //将用户信息写入sharedPreferences中
        SharedPreferencesUtil.CbbUserInfo.setUserInfo(mUser);
    }

    /**
     * 清除用户信息
     */
    public synchronized void clearUser() {
        if (mUser != null) {
            UserInfo users = new UserInfo();
            users.setPhone(mUser.getPhone());
            setUser(users);
        }
    }

    /**
     * 判断用户是否登录
     */
    public boolean getIsLogin() {
        if (getUser() != null && getUser().getID() > 0) {
            return true;
        } else {
            return false;
        }
    }
}
